//
//  CircularReferenceViewController.m
//  ExerciseOC
//
//  Created by 王子曦 on 2025/4/14.
//

#import "CircularReferenceViewController.h"
#import "Person.h"

@interface CircularReferenceViewController ()
@property (nonatomic, strong) UITextView *textView;
@end

@implementation CircularReferenceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"循环引用";
    
    // 创建文本视图
    self.textView = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.textView.editable = NO;
    self.textView.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.textView];
    
    // 设置内容
    NSMutableString *content = [NSMutableString string];
    [content appendString:@"循环引用（Retain Cycle）是iOS中常见的内存泄漏问题\n\n"];
    
    [content appendString:@"1. 什么是循环引用：\n"];
    [content appendString:@"   - 两个或多个对象相互持有强引用\n"];
    [content appendString:@"   - 导致引用计数无法归零\n"];
    [content appendString:@"   - 对象无法被释放，造成内存泄漏\n\n"];
    
    [content appendString:@"2. 常见的循环引用场景：\n"];
    [content appendString:@"   - 父子视图控制器相互引用\n"];
    [content appendString:@"   - delegate代理模式\n"];
    [content appendString:@"   - block块内部使用self\n"];
    [content appendString:@"   - NSTimer与视图控制器\n\n"];
    
    [content appendString:@"3. 解决方案：\n"];
    [content appendString:@"   - 使用weak修饰符\n"];
    [content appendString:@"   - 使用block时使用weakSelf\n"];
    [content appendString:@"   - 合理设计对象之间的关系\n"];
    [content appendString:@"   - 在适当时机手动打破循环\n\n"];
    
    [content appendString:@"4. 代码示例：\n"];
    [content appendString:@"   // 错误示例\n"];
    [content appendString:@"   @property (strong) Person *friend;  // 强引用\n\n"];
    [content appendString:@"   // 正确示例\n"];
    [content appendString:@"   @property (weak) Person *friend;  // 弱引用\n\n"];
    
    [content appendString:@"5. 调试方法：\n"];
    [content appendString:@"   - 使用Instruments的Leaks工具\n"];
    [content appendString:@"   - 观察dealloc是否被调用\n"];
    [content appendString:@"   - 使用内存图分析工具\n"];
    [content appendString:@"   - Debug Memory Graph"];
    
    self.textView.text = content;
}

@end